/**
 * Created by levy on 16/7/4.
 * 不要被react束缚住了
 */
import {shopping} from "../const/shopping";
import {ItemUtil} from "../components/shopping/ItemUtil";
import PullRefresh from "../components/mui/PullRefresh";
import NoData from "../components/NoData";

const lf = liefeng,
    R = React,
    RC = React.createClass,
    ajax = lf.utils.ajax;

const api = shopping.api,
    MAX_PRICE = 20000 * 100; //2w元, 分为单位

//注意价格的计算全用分
let totalPrice = 0;

// /**
//  * 最大金额不能超过 MAX_PRICE
//  * @returns {boolean}
//  */
// const checkMaxPrice = function () {
//     if(totalPrice > MAX_PRICE) {
//         alert('最大金额不能超过' + MAX_PRICE/100 + '元');
//         return false;
//     }
//     return true;
// };

/**
 * 更新已经选择商品数量
 * @param count
 * @param isAdd true: add; false: minus
 */
const updateSelectedCount = function (count, isAdd) {
    let $selected = $('.selected').find('.num'),
        selectedCount = $selected.text() * 1;

    if (isAdd)
        $selected.text(selectedCount + count);
    else
        $selected.text(selectedCount - count);

};

/**
 * @param salePrice
 * @param originPrice
 * @param count
 */
const countPrice = function (salePrice, originPrice, count) {
    let total = parseInt(salePrice * 10 * 10 * count),
        save = parseInt(originPrice * 10 * 10 * count - total);

    return {
        total,
        save
    }
};

/**
 *
 * 更新总价/已省金额
 * @param total 总价金额
 * @param save 已省金额
 * @param $total
 * @param $save
 */
const updatePrice = function (total, save, $total, $save) {
    let currTotal = Math.round($total.text() * 100) || 0,
        currSave = Math.round($save.text() * 100) || 0;

    // console.log('save result: ' + currSave + save);
    $total.text(((currTotal + total) / 100));
    $save.text(((currSave + save) / 100));
};

/**
 * @param goodsId 商品id
 * @param name 商品名字
 */
const toItemDetail = function (goodsId, name) {
    lf.appJs.doAction('shopping-item-detail.html?goodsId=' + goodsId, name);
};


/**
 * props:
 *  id
 *  count
 *  salePrice
 *  originPrice
 */
const CheckBox = RC({
    render() {
        return <div ref="checkbox" className="checkbox" data-id={this.props.id}
                    onTouchEnd={e => this.check(e)}></div>
    },
    check(e) {
        let $checkbox = $(e.target),
            count = this.props.count,
            $total = $('.total-price').find('.num'),
            $save = $('.save-money').find('.num'),
            {total, save} = countPrice(this.props.salePrice, this.props.originPrice, count);


        if (!$checkbox.hasClass('active')) {
            // if($total.text() * 100 + total > MAX_PRICE) {
            //     alert('最大金额不能超过' + MAX_PRICE/100 + '元');
            //     return;
            // }

            updateSelectedCount(count, true);

            updatePrice(total, save, $total, $save)
        }
        else {
            updateSelectedCount(count, false);

            updatePrice(-total, -save, $total, $save)
        }

        $checkbox.toggleClass('active');

        //check-all 样式
        let $checkAll = $('.check-all');
        if ($('.checkbox.active').not($checkAll).length == this.props.itemListLen) {
            $checkAll.addClass('active');
        }
        else
            $checkAll.removeClass('active');
    },
    componentWillReceiveProps(nextProps) {
        if (nextProps.count == this.props.count || !$(R.findDOMNode(this.refs.checkbox)).hasClass('active')) return;

        let count = nextProps.count - this.props.count,
            $total = $('.total-price').find('.num'),
            $save = $('.save-money').find('.num'),
            {total, save} = countPrice(this.props.salePrice, this.props.originPrice, count);

        // if($total.text() * 100 + total > MAX_PRICE) {
        //     alert('最大金额不能超过' + MAX_PRICE/100 + '元');
        //     return;
        // }

        updateSelectedCount(count, true);
        updatePrice(total, save, $total, $save);
    }
});

/**
 * props:
 *  item
 *  itemListLen 商品种类个数
 */
const Item = RC({
    getInitialState() {
        return {
            count: this.props.item.goodsNumber,
        }
    },
    delete() {
        ajax({
            type: 'post',
            url: api.prefix + api.cart.delGoods,
            data: {
                cartId: this.props.item.id,
            }
        }, null, () => {
            //fuck　我直接reload就好了
            // updatePrice();
            // updateSelectedCount(this.state.count, false);
            // lf.appJs.getUser(user => getCartGoods(user));
            window.location.reload();
        });
    },
    add() {
        ajax({
            type: 'post',
            url: api.prefix + api.cart.incrGoods,
            data: {
                cartId: this.props.item.id,
            }
        }, null, () => this.updateNum(true));
    },
    minus() {
        if (this.state.count <= 1) {
            lf.appJs.toast('客官不可以~');
            return;
        }

        ajax({
            type: 'post',
            url: api.prefix + api.cart.descGoods,
            data: {
                cartId: this.props.item.id,
            }
        }, null, () => this.updateNum(false))

    },
    updateNum(flag) {
        let count = this.state.count;

        if (flag)
            this.setState({count: ++count});
        else
            this.setState({count: --count});
    },
    componentDidMount() {
        let $operate = $(R.findDOMNode(this.refs.operate));

        $operate.find('.minus').on('touchend', () => this.minus());

        $operate.find('.add').on('touchend', () => this.add());


        $(R.findDOMNode(this.refs.delete)).on('touchend', () => {
            lf.appJs.confirm('确认删除吗?', this.delete);
        });


        R.findDOMNode(this.refs.img).addEventListener('tap', () => {
            toItemDetail(this.props.item.goodsId, this.props.item.goodsName);
        });

        R.findDOMNode(this.refs.name).addEventListener('tap', () => {
            toItemDetail(this.props.item.goodsId, this.props.item.goodsName);
        });
    },
    render() {
        let item = this.props.item;

        return <div className={"item-box flex "}>
            <CheckBox salePrice={item.promotePrice || item.goodsPrice}
                      originPrice={item.marketPrice}
                      count={this.state.count}
                      itemListLen={this.props.itemListLen}
                      id={item.goodsId}/>
            <div className="item flex border-bottom ">
                <img src={lf.utils.getProtocol() + shopping.imgPre + item.goodsThumb} className="img" ref="img"/>
                <div className="text flex ">
                    <div className="flex col align-start">
                        <p className="name" ref="name">
                            {item.goodsName}
                        </p>
                        <div className="operate flex" ref="operate">
                            <div className="minus"></div>
                            <div className="flex-item num">{this.state.count}</div>
                            <div className="add mui-icon mui-icon-plusempty"></div>
                        </div>
                    </div>
                    <div className="flex col">
                        <p className="sale-price">{ItemUtil.getSalePrice(item)}</p>
                        <p className="origin-price">{ItemUtil.getOriginPrice(item)}</p>
                        <span ref="delete" className="mui-icon mui-icon-trash"/>
                    </div>
                </div>
            </div>
        </div>
    }
});

/**
 * props
 *  itemList
 */
const ItemList = RC({
    render() {
        const itemList = this.props.itemList.map((item, i) => {
            totalPrice += item.goodsPrice * 10 * 10 * item.goodsNumber;

            return <Item key={'item-'+item.goodsId} item={item}
                         itemListLen={this.props.itemList.length}/>
        });

        return <div className="">
            <div className="item-list ">
                {itemList}
            </div>
            <div className="selected border-bottom border-top">已经选择<span className="num">0</span>件商品</div>
        </div>
    }
});

const Fixed = RC({
    checkAll(e) {
        // if(!checkMaxPrice()) return;

        let $checkAll = $(e.target),
            $itemCheck = $('.checkbox').not($checkAll);

        $checkAll.toggleClass('active');

        if ($checkAll.hasClass('active'))
            $itemCheck.not('.active').trigger('touchend');
        else
            $itemCheck.filter('.active').trigger('touchend');

    },
    componentDidMount() {
        $('.confirm-order').on('tap', function () {
            let ids = '';
            $('.checkbox.active').not('.check-all').each(function (i, item) {
                if (i == 0)
                    ids += $(this).data('id');
                else
                    ids += ',' + $(this).data('id');

            });
            if (!ids)
                lf.appJs.toast('请选择商品下单');
            else
                lf.appJs.doAction(`shopping-order-confirm.html?goodsIds=${ids}`, '确认订单');
        });

        $(R.findDOMNode(this.refs.checkAll)).trigger('touchend');
    },
    render() {
        return <div className="fixed-wrapper">
            <div className="fixed-content flex space-between">
                <div className="check-all checkbox" ref="checkAll" onTouchEnd={this.checkAll}>
                    全选
                </div>
                <div>
                    <p className="total-price">总价: ￥<span className="num">0</span></p>
                    <p className="save-money">已省 ￥<span className="num">0</span></p>
                </div>
                <span className="mui-btn shopping-red-bg confirm-order">提交订单</span>
            </div>
        </div>
    }
});

/**
 * props
 *  itemList
 */
const Root = RC({
    render() {

        return <div className="shopping-cart">
            <PullRefresh data={<ItemList itemList={this.props.itemList}/>}/>
            <Fixed/>
        </div>
    },
});


//获取购物车中商品列表
//每次是新数据,才会重新render
const getCartGoods = function (user) {
    ajax({
        url: api.prefix + api.cart.listCartGoods,
        data: {
            custGlobalId: user.globalId || (user.custLoginVo && user.custLoginVo.globalId),
            size: 999,
        }
    }, null, function (data) {
        if (!data.length)
            R.render(<NoData data={{span_text: '购物车还是空的噢~'}}/>,
                document.getElementById('root'), function () {
                });
        else
            R.render(<Root itemList={data}/>,
                document.getElementById('root'));
    });
};

lf.appJs.getUser(user => {
    getCartGoods(user);
    lf.appJs.refresh();
});
